{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import tensorflow_datasets as tfds\n",
    "from t5.data import preprocessors as prep\n",
    "import functools\n",
    "import t5\n",
    "import gin\n",
    "import sentencepiece as spm\n",
    "from glob import glob\n",
    "import os\n",
    "\n",
    "gin.parse_config_file('pretrained_models_base_operative_config.gin')\n",
    "vocab = 'sp10m.cased.ms-en.model'\n",
    "sp = spm.SentencePieceProcessor()\n",
    "sp.Load(vocab)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 689290/689290 [00:00<00:00, 1098628.64it/s]\n"
     ]
    }
   ],
   "source": [
    "# !wget https://f000.backblazeb2.com/file/malay-dataset/normalization/twitter-normalized.json\n",
    "\n",
    "import json\n",
    "\n",
    "with open('twitter-normalized.json') as fopen:\n",
    "    data = json.load(fopen)\n",
    "    \n",
    "X, Y = [], []\n",
    "for i in tqdm(data):\n",
    "    if len(i[0]) and len(i[1]):\n",
    "        X.append(i[0])\n",
    "        Y.append(i[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "def cleaning(string):\n",
    "    string = string.replace('\\n', ' ').replace('\\t', ' ')\n",
    "    string = re.sub(r'[ ]+', ' ', string).strip()\n",
    "    return string"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 689290/689290 [00:18<00:00, 37042.44it/s]\n"
     ]
    }
   ],
   "source": [
    "with tf.io.gfile.GFile('twitter-norm.tsv', \"w\") as outfile:\n",
    "    for i in tqdm(range(len(X))):\n",
    "        l = cleaning(X[i])\n",
    "        r = cleaning(Y[i])\n",
    "        outfile.write(\"%s\\t%s\\n\" % (l, r))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "def social_media_norm_dataset(split, shuffle_files = False):\n",
    "    del shuffle_files\n",
    "    ds = tf.data.TextLineDataset(\n",
    "        [\n",
    "            'twitter-norm.tsv'\n",
    "        ]\n",
    "    )\n",
    "\n",
    "    ds = ds.map(\n",
    "        functools.partial(\n",
    "            tf.io.decode_csv,\n",
    "            record_defaults = ['', ''],\n",
    "            field_delim = '\\t',\n",
    "            use_quote_delim = False,\n",
    "        ),\n",
    "        num_parallel_calls = tf.data.experimental.AUTOTUNE,\n",
    "    )\n",
    "    ds = ds.map(lambda *ex: dict(zip(['question', 'answer'], ex)))\n",
    "    return ds\n",
    "\n",
    "def social_media_norm_preprocessor(ds):\n",
    "    def to_inputs_and_targets(ex):\n",
    "        return {\n",
    "            'inputs': tf.strings.join(['sosial media norm: ', ex['question']]),\n",
    "            'targets': ex['answer'],\n",
    "        }\n",
    "\n",
    "    return ds.map(\n",
    "        to_inputs_and_targets,\n",
    "        num_parallel_calls = tf.data.experimental.AUTOTUNE,\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "t5.data.TaskRegistry.remove('social_media_norm_dataset')\n",
    "t5.data.TaskRegistry.add(\n",
    "    'social_media_norm_dataset',\n",
    "    dataset_fn = social_media_norm_dataset,\n",
    "    splits = ['train'],\n",
    "    text_preprocessor = [social_media_norm_preprocessor],\n",
    "    sentencepiece_model_path = vocab,\n",
    "    metric_fns = [t5.evaluation.metrics.accuracy],\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "nq_task = t5.data.TaskRegistry.get(\"social_media_norm_dataset\")\n",
    "ds = nq_task.get_dataset(split='paraphrase.tsv', sequence_length={\"inputs\": 1024, \"targets\": 1024})\n",
    "r = tfds.as_numpy(ds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'inputs_plaintext': b'sosial media norm: @nawmianIdris Ada dua jalan kan dulu takde rb polis. Ioi dgn putrajaya sentral. Now da ada.',\n",
       " 'inputs': array([  969,   295, 19048,    31,  1121,   476,   806,  1676,    47,\n",
       "          133,  8354,    16,  2540,   192,   489,    13,   103,  5891,\n",
       "         2427,   429,    13, 13060,   612,     3,    59,  9303,    13,\n",
       "           79,   353,   152,    13, 19152,  8948,  2234,  6313,     3,\n",
       "         1514,    13,   530,    97,     3,     1]),\n",
       " 'targets_plaintext': b'@nawmianIdris Ada dua jalan kan dahulu tiada rb polis . Ioi dengan putrajaya sentral . Now da ada .',\n",
       " 'targets': array([ 1121,   476,   806,  1676,    47,   133,  8354,    16,  2540,\n",
       "          192,   489,    13,   103,  3544,  3006,    13, 13060,   612,\n",
       "           13,     3,    59,  9303,    28,    13, 19152,  8948,  2234,\n",
       "         6313,    13,     3,  1514,    13,   530,    97,    13,     3,\n",
       "            1])}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "next(r)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
